﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WxCore.Sqlsugar
{

    /// <summary>
    /// 
    /// </summary>
    public class SqlSugarHelper
    {
        public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig
        {
            ConnectionString = DbSetting.ConnectionString,
            DbType = getCurrentDbType(DbSetting.DbType),
            InitKeyType = InitKeyType.Attribute,
            IsAutoCloseConnection = true
        }, delegate (SqlSugarClient db)
        {
            db.Aop.OnLogExecuting = delegate (string sql, SugarParameter[] pars)
            {
                Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary((SugarParameter it) => it.ParameterName, (SugarParameter it) => it.Value)));
                Console.WriteLine();
            };
            db.Aop.OnLogExecuted = delegate (string sql, SugarParameter[] pars)
            {
                if (db.Ado.SqlExecutionTime.TotalSeconds > 1.0)
                {
                    string firstFileName = db.Ado.SqlStackTrace.FirstFileName;
                    int firstLine = db.Ado.SqlStackTrace.FirstLine;
                    string firstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
                }
            };
        });

        private static DbType getCurrentDbType(string dbTypeStr)
        {
            DbType result = DbType.MySql;
            switch (dbTypeStr.ToLower())
            {
                case "sqlserver":
                    result = DbType.SqlServer;
                    break;
                case "mysql":
                    result = DbType.MySql;
                    break;
                case "sqlite":
                    result = DbType.Sqlite;
                    break;
                case "oracle":
                    result = DbType.Oracle;
                    break;
            }

            return result;
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class DbSetting
    {
        /// <summary>
        /// 
        /// </summary>
        public static string ConnectionString { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public static string DbType { get; set; }
    }
}
